<template>
    <div>
        <el-button class="button-container" type="text" @click="dialogFormVisible = true">
            登录
        </el-button>
        <el-dialog title="用户登录" :visible.sync="dialogFormVisible" center>
            <el-form :model="form" label-position="left" :rules="rules" :label-width="formLabelWidth" ref="form">
                <el-form-item label="用户名" prop="username" :error="error.username">
                    <el-input v-model="form.username" placeholder="请输入用户名"
                              @keydown.enter.native="submitForm('form')"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password" :error="error.password">
                    <el-input v-model="form.password" show-password placeholder="请输入密码"
                              @keydown.enter.native="submitForm('form')"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm('form')">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {stringify} from "qs";
    import {state} from "../../api/exception";

    export default {
        name: "LoginBox",
        data(){
            return {
                dialogFormVisible: false,
                formLabelWidth: "12rem",
                form: {
                    username: undefined,
                    password: undefined,
                },
                error: {
                    username: undefined,
                    password: undefined,
                },
                rules:{
                    username: [
                        {required: true, message: '请输入用户名', trigger: ['blur', 'change']},
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: ['blur', 'change']},
                    ],
                }
            }
        },
        methods: {
            /**
             * 提交表单
             * @param formName 表单
             */
            async submitForm(formName) {
                this.$refs[formName].validate(async (valid) => {
                    if (valid) {
                        let flag = await this.afterCallApi();
                        if(flag){
                            // 获取用户信息
                            await this.$store.dispatch("user/getInfo", {fields: "email,avatar,nickname"});
                            this.$msg.success("登录成功");
                            setTimeout(() => {
                                // 设置登录状态
                                this.$store.commit("user/setIsLogin", true);
                                // 关闭窗口
                                this.dialogFormVisible = false;
                            }, 500);
                        }
                    }
                });
            },
            /**
             * 调用api之后的处理工作
             */
            async afterCallApi() {
                let params = stringify({
                    username: this.form.username,
                    password: this.form.password,
                });
                let resp = await this.$store.dispatch("user/login", params);
                let code = resp.code;
                let message = resp.message;
                let isSuccess = false;
                // 判断code值，成功则将标志位设为true，失败则设置失败提示语
                if (code == state.Success) {
                    isSuccess = true;
                } else if (code == state.UserNotExistException) {
                    this.error.username = message;
                } else if (code == state.PasswordNotMatchException) {
                    this.error.password = message;
                } else {
                    this.$msg.error(message);
                }
                return isSuccess;
            },
            /**
             * 重置表单
             * @param formName 表单
             */
            resetForm(formName) {
                this.$refs[formName].resetFields();
            }
        },
        watch: {
            /**
             * 关闭窗口时重置数据
             */
            dialogFormVisible: {
                handler(newValue) {
                    if (!newValue) {
                        setTimeout(() => {
                            this.resetForm('form');
                        }, 500);
                    }
                }
            },
        }
    }
</script>

<style scoped>
    .button-container{
        color: #909399;
    }
    .button-container:hover{
        color: #303133;
    }
</style>